package com.lihang0328.groupmessageangel;

import android.Manifest;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import static com.lihang0328.groupmessageangel.FileUtils.DoHaveName;

public class AddContract extends AppCompatActivity {
    private Button bt_add;
    private EditText etName;
    private EditText etPhone;
    private int comeFrom = 1;
    private String EXCEL_PATH="";
    private final int REQUEST_CODE_ASK_CALL_WRITECON = 10012;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        if (getIntent() != null) {
            EXCEL_PATH = getIntent().getStringExtra("PATH");
            comeFrom = Integer.parseInt(getIntent().getStringExtra("ORIGIN"));
        }
        bt_add = findViewById(R.id.btn_choose);
        etName = findViewById(R.id.et_PName);
        etPhone = findViewById(R.id.et_PPhone);
        ensureWrite();
        bt_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addContact( etName.getText().toString(), etPhone.getText().toString());
                Bundle bundle=new Bundle();
                bundle.putString("PATH",EXCEL_PATH);
                bundle.putString("ORIGIN",String.valueOf(comeFrom));
                Intent intent=new Intent(AddContract.this, ContextActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
//                finish();
            }
        });
    }

    /**
     * 添加联系人
     * @param name
     * @param phoneNumber
     */
    public void addContact(String name, String phoneNumber) {
        System.out.println("lihangadd: " + name + " " + phoneNumber);
        if(DoHaveName(this, name)) return;
        // 创建一个空的ContentValues
        ContentValues values = new ContentValues();
        Context context = this;
        // 向RawContacts.CONTENT_URI空值插入，
        // 先获取Android系统返回的rawContactId
        // 后面要基于此id插入值
        Uri rawContactUri = context.getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);
        values.clear();
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        // 内容类型
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        // 联系人名字
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
        // 向联系人URI添加联系人名字
        context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        values.clear();

        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        // 联系人的电话号码
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
        // 电话类型
        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        // 向联系人电话号码URI添加电话号码
        context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        values.clear();

        //以下为插入e-mail信息，不需要可以注释掉
//        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
//        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
//        // 联系人的Email地址
//        values.put(ContactsContract.CommonDataKinds.Email.DATA, "zhangphil@xxx.com");
//        // 电子邮件的类型
//        values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK);
//        // 向联系人Email URI添加Email数据
//        context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        Toast.makeText(AddContract.this, "联系人数据添加成功", Toast.LENGTH_SHORT).show();
    }
    /**
     * 判断修改联系人权限是否开启
     */
    private void ensureWrite() {
        int checkSendEmailPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS);
        System.out.println("lihangensuresend: " + checkSendEmailPermission);
        if(checkSendEmailPermission != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_CONTACTS},REQUEST_CODE_ASK_CALL_WRITECON);
        }
    }
    /**
     * 申请权限结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        System.out.println("lihangen: " + requestCode);
        switch (requestCode) {
            case REQUEST_CODE_ASK_CALL_WRITECON:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    Toast.makeText(AddContract.this, "无修改联系人权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
